import os
import sys
from pathlib import Path

from PyQt5 import QtGui
from PyQt5.QtCore import pyqtSignal

from PyQt5.QtWidgets import QTabWidget, QWidget, QVBoxLayout, QGridLayout, QLabel, QLineEdit, QPushButton, QTextEdit, \
    QFileDialog, QApplication

from FileTree import FileCheckTreeWidget
import util

TAB_SELECTION = 'tab_selection'
FILE_LIST = 'file_list'
TAB_CHOOSE_USE_CHECK = 0
TAB_CHOOSE_USE_FILE_LIST = 1

def update_selection(index: int):
    util.write_config({TAB_SELECTION: index.__str__()})


class SheetChooseWidget(QWidget):
    def __init__(self):
        super(SheetChooseWidget, self).__init__()
        self.tab_widget = None
        self.file_check_widget = None
        self.file_list_widget = None
        self.init_ui()
        self.load_config()

    def init_ui(self):
        layout = QVBoxLayout()
        self.file_list_widget = FileListWidget()
        self.file_check_widget = FileCheckTreeWidget()
        self.tab_widget = QTabWidget()
        self.tab_widget.addTab(self.file_check_widget, '手动文件选择')
        self.tab_widget.addTab(self.file_list_widget, '列表文件选择')
        self.tab_widget.currentChanged.connect(update_selection)
        layout.addWidget(self.tab_widget)
        self.setLayout(layout)

    def load_config(self):
        last_tab = util.get_config(TAB_SELECTION)
        if last_tab:
            self.tab_widget.setCurrentIndex(int(last_tab))

    def get_cur_choose(self):
        return self.tab_widget.currentIndex()

    def update_file_tree_path(self, path):
        self.file_check_widget.set_root_path(path)


class Drag_Text(QTextEdit):
    file_signal = pyqtSignal(str)
    def __init__(self):
        super(Drag_Text, self).__init__()
        self.init_ui()
    def init_ui(self):
        self.setAcceptDrops(True)

    def dragEnterEvent(self, e: QtGui.QDragEnterEvent) -> None:
        if e.mimeData().hasFormat("text/uri-list"):
            e.acceptProposedAction()


    def dropEvent(self, e: QtGui.QDropEvent) -> None:
        urls = e.mimeData().urls()
        if urls == "":
            return
        fileName = urls.pop().toLocalFile()
        if fileName == "":
            return
        file = Path(fileName)
        if file.exists() and file.is_file():
            self.setText(Path(file).read_text())
            self.file_signal.emit(file.__str__())

class FileListWidget(QWidget):
    def __init__(self):
        super(FileListWidget, self).__init__()
        self.file_list_show = None
        self.btn_filelist = None
        self.file_list_edit = None
        self.file_list_label = None
        self.init_ui()
        self.load_config()

    def init_ui(self):
        layout = QGridLayout()
        self.file_list_label = QLabel('目标列表')
        self.file_list_edit = QLineEdit()
        self.file_list_edit.setReadOnly(True)
        self.btn_filelist = QPushButton('选择合并文件列表(.txt)')
        self.btn_filelist.setToolTip("选择要合并的文件列表文件，内容为合并的Excel文件名")
        self.file_list_show = Drag_Text()
        self.btn_filelist.pressed.connect(self.choose_file_list)
        layout.addWidget(self.file_list_label, 1, 0)
        layout.addWidget(self.file_list_edit, 1, 1)
        layout.addWidget(self.btn_filelist, 1, 2)
        layout.addWidget(self.file_list_show, 2, 1, 5, 2)
        self.file_list_edit.textChanged.connect(lambda: util.write_config({FILE_LIST: self.file_list_edit.text()}))
        self.file_list_show.file_signal.connect(self.change_file)
        self.setLayout(layout)

    def change_file(self,file:str):
        if not Path(file).exists() or not Path(file).is_file():
            return
        self.file_list_edit.setText(file)

    def load_config(self):
        file_list = util.get_config(FILE_LIST)
        if file_list:
            self.file_list_edit.setText(file_list)


    def choose_file_list(self):
        file_name_choose, filetype = QFileDialog.getOpenFileName(self,
                                                                 "选取文件",
                                                                 Path.cwd().__str__(),  # 起始路径
                                                                 "Text Files (*.txt)")  # 设置文件扩展名过滤,用双分号间隔

        if file_name_choose == "":
            util.my_logger.debug("\n取消选择")
            return

        self.file_list_edit.setText(file_name_choose.replace('/', os.sep))
        util.my_logger.debug("\n你选择的文件为:{}".format(self.file_list_edit.text()))
        util.my_logger.debug("文件筛选器类型: {}".format(filetype))
        try:
            if Path(file_name_choose).exists():
                self.file_list_show.setText(Path(file_name_choose).read_text())
        except Exception as e:
            util.my_logger.debug(e.__repr__())
            return


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainForm = SheetChooseWidget()
    mainForm.show()

    sys.exit(app.exec_())
